package com.kq.myofficialaccount.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kq.myofficialaccount.model.message.TestMessage;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 */
public class WxUtil {


    /**
     * 将返回的信息封装为 xml
     */
    public static String getReplyMessage(Map<String, String> map, String message) throws JsonProcessingException {
        // 设置基础的信息
        TestMessage testMessage = new TestMessage();
        testMessage.setFromUserName(map.get("ToUserName"));
        testMessage.setToUserName(map.get("FromUserName"));
        testMessage.setMsgType("text");
        testMessage.setCreateTime(System.currentTimeMillis() / 1000);
        //设置需要返回给用户的信息
        testMessage.setContent(message);
        // 利用 JackSon 实现序列化
        return JsonUtil.getXmlString(testMessage);
    }

    /**
     * 获取带信息的二维码的方法
     */
    public static String getTemporaryQRCode(Boolean isTemplate, Boolean isSTR) throws JsonProcessingException {
        HashMap<String, Object> map = new HashMap<>();
        //获取临时二维码
        //该二维码有效时间，以秒为单位。
        //最大不超过2592000（即30天），此字段如果不填，则默认有效期为60秒。
        map.put("expire_seconds", 120);
        if (isTemplate) {
            //二维码类型，QR_SCENE为临时的整型参数值,QR_STR_SCENE为临时的字符串参数值，
            // QR_LIMIT_SCENE为永久的整型参数值,QR_LIMIT_STR_SCENE为永久的字符串参数值
            if (isSTR) {
                map.put("action_name", "QR_STR_SCENE");
            }else {
                map.put("action_name", "QR_SCENE");
            }
        } else {
            if (isSTR) {
                map.put("action_name", "QR_LIMIT_STR_SCENE");
            } else {
                map.put("action_name", "QR_LIMIT_SCENE");
            }
        }
        // 构建 actionInfo
        HashMap<String, Object> actionInfo = new HashMap<>();
        HashMap<String, Object> scene = new HashMap<>();
        scene.put("scene_id", "1");
        actionInfo.put("scene", scene);
        map.put("action_info", actionInfo);
        //发送请求来获取 ticket
        String ticket = getTicket(map);
        // 通过 ticket 来获取到二维码的地址
        String encode = URLEncoder.encode(ticket);
        String codeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + encode;
        return codeUrl;
    }

    public static String getTicket(Map map) throws JsonProcessingException {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        // 将字符串转化为 json 格式
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(map);

        HttpResponse execute = HttpUtil.createPost(url)
                .body(jsonString)
                .execute();
        Map<String, String> paramMap = JsonUtil.getParamMap(execute.body());
        return paramMap.get("ticket");
    }

    /**
     * 获取 accessToken
     */
    public static String getAccessToken() throws JsonProcessingException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=wxe0bcbf641793d870" +
                "&secret=fc187b89058f51ba8c92da465671ba8d";
        HttpResponse execute = HttpUtil.createGet(url)
                .execute();
        String body = execute.body();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> stringObjectMap = objectMapper.readValue(body,
                new TypeReference<>(){});
        return (String)stringObjectMap.get("access_token");
    }

    /**
     * 获取用户的基本信息
     */
    public static Map<String, String> getUserBaseMes(String openId) throws JsonProcessingException {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info" +
                "?access_token" + accessToken +
                "&openid=" + openId +
                "&lang=zh_CN";
        HttpResponse execute = HttpUtil.createGet(url).execute();
        return JsonUtil.getParamMap(execute.body());
    }
}
